package com.sc.nft.util.aliPay.AlipayCore;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.sc.nft.util.aliPay.config.AlipayConfigMeTaGo;

import static com.sc.nft.util.aliPay.config.AlipayConfig.*;


public class AliPayCore {

    private static final String PRODUCT_CODE_APP = "QUICK_MSECURITY_PAY";



    /**
     * SDK 生成 APP 支付订单信息示例
     */
    public static String getSdkParams(String outTradeNo,String amount, String timeExpire) {
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                app_id, private_key, "json", input_charset, ali_public_key, sign_type);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("数字商品费用");
        model.setSubject("数字商品");
        model.setOutTradeNo(outTradeNo);
        //过期时间分钟
//        model.setTimeoutExpress("5m");
        //最晚支付时间
        model.setTimeExpire(timeExpire);
        model.setTotalAmount(amount);
        model.setProductCode(PRODUCT_CODE_APP);
        request.setBizModel(model);
//        request.setNotifyUrl("http://51982606t2.zicp.fun/order/alipaySyn");
        request.setNotifyUrl(server_url);
        String rs = null;
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            //就是orderString 可以直接给客户端请求，无需再做处理
            rs = response.getBody();
            System.out.println(rs);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return rs;
    }
    public static String getSdkParamsMetaGo(String outTradeNo,String amount, String timeExpire) {
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                AlipayConfigMeTaGo.app_id, AlipayConfigMeTaGo.private_key, "json", AlipayConfigMeTaGo.input_charset,AlipayConfigMeTaGo.ali_public_key, AlipayConfigMeTaGo.sign_type);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("数字商品费用");
        model.setSubject("数字商品");
        model.setOutTradeNo(outTradeNo);
        //最晚支付时间
        model.setTimeExpire(timeExpire);
        model.setTotalAmount(amount);
        model.setProductCode(PRODUCT_CODE_APP);
        request.setBizModel(model);
//        request.setNotifyUrl("http://51982606t2.zicp.fun/order/alipaySyn");
        request.setNotifyUrl(AlipayConfigMeTaGo.server_url);
        String rs = null;
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            //就是orderString 可以直接给客户端请求，无需再做处理
            rs = response.getBody();
//            System.out.println(rs);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return rs;
    }
    public static String getSdkParamsMetaGoWeb(String outTradeNo,String amount, String timeExpire) {
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                AlipayConfigMeTaGo.app_id, AlipayConfigMeTaGo.application_private_key, "json",
                AlipayConfigMeTaGo.input_charset,AlipayConfigMeTaGo.public_key, AlipayConfigMeTaGo.sign_type);

        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();

        model.setBody("数字商品费用");
        model.setSubject("数字商品");
        model.setOutTradeNo(outTradeNo);
        //最晚支付时间
        model.setTimeExpire(timeExpire);
        model.setTotalAmount(amount);
        model.setProductCode("QUICK_WAP_WAY");
        request.setBizModel(model);
        request.setNotifyUrl(AlipayConfigMeTaGo.server_url);
        String rs = null;
        try {
            rs = alipayClient.pageExecute(request, "GET").getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return rs;
    }



    public static Integer getRs(String orderNo) throws Exception {
        Integer flag = 1;
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                app_id, private_key, "json", input_charset, ali_public_key, sign_type);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no", orderNo);
        request.setBizContent(jsonObject.toJSONString());
        AlipayTradeQueryResponse response = alipayClient.execute(request);
//        System.out.println(response.getBody());
//        System.out.println(response.getBody());
        if (response.isSuccess()) {
//            System.out.println("调用成功");
            JSONObject jsonObject1 = JSONObject.parseObject(response.getBody());
            JSONObject alipay_trade_query_response = jsonObject1.getJSONObject("alipay_trade_query_response");
            String code = alipay_trade_query_response.getString("code");
            if (code.equals("10000")) {
                String trade_status = alipay_trade_query_response.getString("trade_status");
                if(trade_status.equals("TRADE_SUCCESS")||trade_status.equals("TRADE_FINISHED")) {//付钱成功
                    flag=1;
                }else if(trade_status.equals("TRADE_CLOSED")){//未支付
                    flag=2;
                }else if(trade_status.equals("TRADE_NOT_EXIST")){//未支付
                    flag=2;
                }else {
                    flag=3;
                }
            }else {
                flag = 3;
            }
        } else {
//            System.out.println("调用失败");
            flag = 3;
        }
        return flag;
    }
    public static Integer getRsMeTaGo(String orderNo) throws Exception {
        Integer flag = 1;
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                AlipayConfigMeTaGo.app_id, AlipayConfigMeTaGo.private_key, "json", AlipayConfigMeTaGo.input_charset, AlipayConfigMeTaGo.ali_public_key, AlipayConfigMeTaGo.sign_type);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no", orderNo);
        request.setBizContent(jsonObject.toJSONString());
        AlipayTradeQueryResponse response = alipayClient.execute(request);
//        System.out.println(response.getBody());
//        System.out.println(response.getBody());
        if (response.isSuccess()) {
//            System.out.println("调用成功");
            JSONObject jsonObject1 = JSONObject.parseObject(response.getBody());
            JSONObject alipay_trade_query_response = jsonObject1.getJSONObject("alipay_trade_query_response");
            String code = alipay_trade_query_response.getString("code");
            if (code.equals("10000")) {
                String trade_status = alipay_trade_query_response.getString("trade_status");
                if(trade_status.equals("TRADE_SUCCESS")||trade_status.equals("TRADE_FINISHED")) {//付钱成功
                    flag=1;
                }else if(trade_status.equals("TRADE_CLOSED")){//未支付
                    flag=2;
                }else if(trade_status.equals("TRADE_NOT_EXIST")){//未支付
                    flag=2;
                }else {
                    flag=3;
                }
            }else {
                flag = 3;
            }
        } else {
//            System.out.println("调用失败");
            flag = 3;
        }
        return flag;
    }


    /**
     * 退款
     * @param tradeNo  支付宝交易号
     * @param refundAmount 退款金额
     * @param outRequestNo 退款请求号
     */
    public static Boolean AlipayTradeRefundRequest(String tradeNo,String refundAmount,String outRequestNo) throws AlipayApiException {//app_id, private_key, "json", input_charset, ali_public_key, sign_type
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",app_id, private_key, "json", input_charset, ali_public_key, sign_type);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", tradeNo);
        bizContent.put("refund_amount", refundAmount);
        bizContent.put("out_request_no", outRequestNo);

        Boolean flag = true;
        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
            return flag;
        } else {
            System.out.println("调用失败");
            flag = false;
        }
        return flag;
    }

    /**
     *  退款结果查询
     * @param tradeNo  支付宝交易号
     * @param outRequestNo 退款请求号
     */
    public static Boolean AlipayTradeFastpayRefundQueryRequest(String tradeNo,String outRequestNo) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",app_id, private_key, "json", input_charset, ali_public_key, sign_type);
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", tradeNo);
        bizContent.put("out_request_no", outRequestNo);

        //// 返回参数选项，按需传入
        //JSONArray queryOptions = new JSONArray();
        //queryOptions.add("refund_detail_item_list");
        //bizContent.put("query_options", queryOptions);

        Boolean flag = true;
        request.setBizContent(bizContent.toString());
        AlipayTradeFastpayRefundQueryResponse response = null;
        response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            flag = false;
        }

        return flag;
    }

    /**
     * JAVA 服务端验证异步通知信息参数示例
     * 回调接口 接收到支付宝返回的request
     */
//    public static Map<String, String> getTz(HttpServletRequest request) {
//        //获取支付宝POST过来反馈信息
//        //把参数全部组装进map
//        Map<String, String> paramMap = new HashMap<String, String>();
//        Enumeration enu = request.getParameterNames();
//        while (enu.hasMoreElements()) {
//            String paramName = (String) enu.nextElement();
//            paramMap.put(paramName, request.getParameter(paramName));
//        }
//        //解析params 得到回调的 状态 订单详情
//
//        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
//        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
//        boolean flag = false;
//        try {
////            flag = WeChatUtil.getSignVeryfy(paramMap, public_key);
//            flag= AlipayNotify.verify(paramMap);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        if (flag) {
//            return paramMap;
//        } else {
//            return null;
//        }
//    }


}
